class Solution
{
public:
    int findShortestSubArray(vector<int> &nums)
    {
        unordered_map<int, int> numsCount;
        for (int num : nums)
        {
            if (numsCount.find(num) != numsCount.end())
            {
                ++numsCount[num];
            }
            else
            {
                numsCount[num] = 1;
            }
        }
        int maxCount = 0;
        vector<int> maxCountNums;
        for (auto &numCountPair : numsCount)
        {
            if (numCountPair.second > maxCount)
            {
                maxCount = numCountPair.second;
                maxCountNums.clear();
                maxCountNums.push_back(numCountPair.first);
            }
            else if (numCountPair.second == maxCount)
            {
                maxCountNums.push_back(numCountPair.first);
            }
        }
        if (maxCount == 1)
        {
            return 1;
        }

        int minSubLen = nums.size();
        for (int maxCountNum : maxCountNums)
        {
            int beginIndex = 0;
            int endIndex = nums.size() - 1;
            while (nums[beginIndex] != maxCountNum)
            {
                ++beginIndex;
            }
            while (nums[endIndex] != maxCountNum)
            {
                --endIndex;
            }
            int subLen = endIndex - beginIndex + 1;
            if (subLen < minSubLen)
            {
                minSubLen = subLen;
            }
        }
        return minSubLen;
    }
};